<template>
	<div style="margin-right: 30px">
		<el-form ref="formObj" :model="wyform" :rules="rules" label-width="100px">
		  <el-form-item label="家庭编号" prop="fid">
		    <el-input maxlength="10" v-model="wyform.fid" placeholder="请输入家庭编号"></el-input>
		  </el-form-item>
		  
		  <div class="form-row">
		    <el-form-item class="form-item" label="省" prop="province">
		  	<el-select v-model="wyform.province" @change="onProvinceChange">
		  	  <el-option v-for="province in provinces" :key="province.code" :label="province.name" :value="province.name"></el-option>
		  	</el-select>
		    </el-form-item>
		    <el-form-item class="form-item" label="市" prop="city">
		  	<el-select v-model="wyform.city" @change="onCityChange">
		  	  <el-option v-for="city in cities" :key="city.code" :label="city.name" :value="city.name"></el-option>
		  	</el-select>
		    </el-form-item>
		  </div>
		  <div class="form-row">
		    <el-form-item class="form-item" label="县(区)" prop="county">
		  	<el-select v-model="wyform.county" @change="onCountyChange">
		  	  <el-option v-for="county in counties" :key="county.code" :label="county.name" :value="county.name"></el-option>
		  	</el-select>
		    </el-form-item>
		    <el-form-item class="form-item" label="乡(镇)" prop="township">
		  	<el-select v-model="wyform.township" @change="onTownshipChange">
		  	  <el-option v-for="township in townships" :key="township.code" :label="township.name" :value="township.name"></el-option>
		  	</el-select>
		    </el-form-item>
		  </div>
		  <el-form-item label="村" prop="village">
		    <el-input v-model="wyform.village" placeholder="请输入村名称"></el-input>
		  </el-form-item>

		  <el-form-item label="风险类型">
				 <el-checkbox v-model="wyform.riskMan" label="人力风险" size="large" />
				 <el-checkbox v-model="wyform.riskSubstance" label="物质风险" size="large" />
				<el-checkbox v-model="wyform.riskNature" label="自然风险" size="large" />
				<el-checkbox v-model="wyform.riskFinance" label="金融风险" size="large" />
				<el-checkbox v-model="wyform.riskSocial" label="社会风险" size="large" />
		  </el-form-item>
		  
		  <el-form-item label="风险级别" prop="riskLevel">
		    <el-input maxLength="20" v-model="wyform.riskLevel" placeholder="请输入风险级别"></el-input>
		  </el-form-item>
		  
		  <el-form-item label="风险备注" prop="riskRemark">
		    <el-input maxLength="20" v-model="wyform.riskRemark" placeholder="请输入风险备注"></el-input>
		  </el-form-item>
		  
		  <el-form-item>
		    <el-button type="primary" plain :icon="Save" @click="save">保存</el-button>
		  </el-form-item>
		</el-form>
	</div>
</template>

<script setup>
	import { ref ,onMounted ,watch ,reactive} from 'vue'
	import Save from '@/components/icons/lssave'
	import areaData from '@/area/pcas-code.json'
	import { get, post } from '@/axios'
	import url from './util'
	import { getPath } from '@/util'
	import { PictureFilled } from '@element-plus/icons-vue'
	import { userIdStore } from '@/stores'
	const idStore = userIdStore()
	const emits = defineEmits(['update:show', 'getTableData'])
	const props = defineProps(['id'])
	const wyform = reactive({
		id: null,
	  ccId: idStore.userId,
	  fid:null,
	  province: '',
	  city: '',
	  county: '',
	  township: '',
	  village: '',
	  riskMan: false,
	  riskSubstance:false,
	  riskNature:false,
	  riskFinance:false,
	  riskSocial:false,
	  riskLevel:null,
	  riskRemark:'',
	  verify:false,
	  rid:null
	})
	const rules = reactive({
		fid: [
			{ required: true, message: '请输入家庭编号', trigger: 'blur' },
			{ pattern: /^\d{10}$/, message: '请输入合理的贫困户编号',trigger: 'blur' },
			{ validator: check, message: '该家庭存在未失效的线索',trigger: 'blur' }
		],
		county: [
			{ required: true, message: '请选择所在县(区)', trigger: 'blur' }
		],
		city: [
			{ required: true, message: '请选择所在城市', trigger: 'blur' }
		],
		province: [
			{ required: true, message: '请选择所在省份', trigger: 'blur' }
		],
		township: [
			{ required: true, message: '请选择所在乡(镇)', trigger: 'blur' }
		],
		village: [
			{ required: true, message: '请输入所在村庄', trigger: 'blur' }
		],
		riskLevel: [
			{ required: true, message: '请输入风险级别', trigger: 'blur' }
		],
		riskRemark: [
			{ required: true, message: '请输入风险备注', trigger: 'blur' }
		],
		verify: [
			{ required: true, message: '请选择是否核实', trigger: 'blur' }
		]
	})
	const formObj = ref()
	if (props.id) {
		wyform.id = props.id
		getById()
	}
	function check (rule, value, callback) {
		get(url.check, { id: props.id, fId: value }, content => {
			if (content) {
				callback()
			} else {
				callback(new Error())
			}
		})
	}
	function save() {
		post(props.id ? url.update : url.add, wyform, content => {
			emits('update:show', false)
			emits('getTableData')
		}, formObj)
	}
	function getById () {
		get(url.getById, { id: props.id }, content => {
			for (const key in wyform) {
				if (Object.prototype.hasOwnProperty.call(content, key)) {
					wyform[key] = content[key]
				}
			}
			if (wyform.province) {
			    // 初始化市级数据
			    const selectedProvince = provinces.value.find(province => province.name === wyform.province);
			    if (selectedProvince) {
			      cities.value = selectedProvince.cities.map(city => ({
			        name: city.name,
			        code: city.code,
			        counties: city.children || [],
			      }));
			    }
			
			    if (wyform.city) {
			      // 初始化县级数据
			      const selectedCity = cities.value.find(city => city.name === wyform.city);
			      if (selectedCity) {
			        counties.value = selectedCity.counties.map(county => ({
			          name: county.name,
			          code: county.code,
			          townships: county.children || [],
			        }));
			      }
			
			      if (wyform.county) {
			        // 初始化乡级数据
			        const selectedCounty = counties.value.find(county => county.name === wyform.county);
			        if (selectedCounty) {
			          townships.value = selectedCounty.townships.map(township => ({
			            name: township.name,
			            code: township.code,
			          }));
			        }
			      }
			    }
			  }
		})
	}
	
	const provinces = ref([]);
	const cities = ref([]);
	const counties = ref([]);
	const townships = ref([]);
	
	onMounted(() => {
	  provinces.value = areaData.map(province => ({
	    name: province.name,
	    code: province.code,
	    cities: province.children || [],
	  }));
	});
	
	// 选择省份后加载市
	const onProvinceChange = (value) => {
	  wyform.province = value;
	  wyform.city = '';
	  wyform.county = '';
	  wyform.township = '';
	  
	  const selectedProvince = provinces.value.find(province => province.name === value);
	
	  if (selectedProvince) {
	    cities.value = selectedProvince.cities.map(city => ({
	      name: city.name,
	      code: city.code,
	      counties: city.children || [],
	    }));
	  } else {
	    cities.value = [];
	  }
	
	  counties.value = [];
	  townships.value = [];
	  wyform.rid = null;
	};
	
	// 选择市后加载县
	const onCityChange = (value) => {
	  wyform.city = value;
	  wyform.county = '';
	  wyform.township = '';
	
	  const selectedCity = cities.value.find(city => city.name === value);
	
	  if (selectedCity) {
	    counties.value = selectedCity.counties.map(county => ({
	      name: county.name,
	      code: county.code,
	      townships: county.children || [],
	    }));
	  } else {
	    counties.value = [];
	  }
	
	  townships.value = [];
	  wyform.rid = null;
	};
	
	// 选择县后加载乡
	const onCountyChange = (value) => {
	  wyform.county = value;
	  wyform.township = '';
	
	  const selectedCounty = counties.value.find(county => county.name === value);
	
	  if (selectedCounty) {
	    townships.value = selectedCounty.townships.map(township => ({
	      name: township.name,
	      code: township.code,
	    }));
	  } else {
	    townships.value = [];
	  }
	
	  wyform.rid = null;
	};
	
	// 选择乡镇后绑定 rId
	const onTownshipChange = (value) => {
	  wyform.township = value;
	  const townshipData = townships.value.find(township => township.name === value);
	  wyform.rid = townshipData ? townshipData.code : null;
	  
	};
</script>

<style scoped lang="scss">
</style>